<template>
	<div class="pound-container">

		<div class="pound-bottom">

			<el-card>

				<template #header>
					<div style="display: flex;justify-content: space-between;">
						<div class="card-header" style="font-size: 24px;font-weight: 550;">
							<span>货物列表</span>
						</div>
						<div>
							<el-icon :size="28" @click="newlist">
								<Plus />
							</el-icon>

						</div>
					</div>

				</template>
				<div class="search-container" style="margin-bottom: 16px; display: flex; gap: 16px; align-items: center;">
				          <!-- 货物名称检索 -->
				          <el-form-item label="货物名称" style="margin-bottom: 0;">
				            <el-input 
				              v-model="searchForm.cargoName" 
				              placeholder="请输入货物名称" 
				              style="width: 200px;" 
				              clearable  
				            />
				          </el-form-item>
				
				          <!-- 规格检索 -->
				          <el-form-item label="规格" style="margin-bottom: 0;">
				            <el-input 
				              v-model="searchForm.specifications" 
				              placeholder="请输入规格" 
				              style="width: 200px;" 
				              clearable 
				            />
				          </el-form-item>
				
				          <!-- 操作按钮 -->
				          <div style="margin-left: auto;">
				            <el-button type="primary" @click="fetchData">查询</el-button>
				            <el-button @click="resetSearch">重置</el-button>
				          </div>
				        </div>
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="createTime" label="创建时间" width="200" />
					<el-table-column prop="cargoName" label="货物名称" />
					<el-table-column prop="specifications" label="规格" />
				<!-- 	<el-table-column prop="tare" label="皮重扣重" />
					<el-table-column prop="roughWeight" label="毛重扣重" />
					<el-table-column prop="suttle" label="净重扣重" /> -->
					<el-table-column label="操作" width="150" fixed="right">
						<template #default="scope">
							<el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
							<!-- <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button> -->
						</template>
					</el-table-column>
				</el-table>



				<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
					<el-pagination v-if="total>0" v-model:current-page="listQuery.current"
						v-model:page-size="listQuery.size" :page-sizes="[5, 8, 10]" :size="size" :background="false"
						layout="sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
						@current-change="handleCurrentChange" />
				</div>
			</el-card>



		</div>

	</div>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
		<el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">


			<el-form-item label="货物名称" prop="cargoName">
					<el-input v-model="formData.cargoName" placeholder="请输入货物名称" style="width: 180px;" />
			<!-- 	<el-select v-model="formData.cargoName" filterable allow-create
					default-first-option :reserve-keyword="false" placeholder="请输入或选择货物名称"
					style="width: 180px" @change="(val) => handleCargoChange(val, formData)"  value-key="id">
					<el-option v-for="item in cargoOptions" :key="item.cargoName" :label="item.cargoName"
						:value="item.cargoName"  >
						<span style="float: left">{{ item.cargoName }}</span>
						      
						   
						</el-option>
				</el-select> -->
				
			</el-form-item>

			<el-form-item label="规格" prop="specifications">
				<el-input v-model="formData.specifications" placeholder="请输入规格" style="width: 180px;" />
			</el-form-item>
			<!-- <el-form-item label="皮重扣重" prop="tare">
				<el-input-number v-model="formData.tare" :min="-9999" :max="9999" :precision="3" :step="0.001"
					controls-position="right" placeholder="±值" style="width: 180px;" />
				<span style="margin-left: 8px; color: #666;">吨（±值）</span>
			</el-form-item>
			<el-form-item label="毛重扣重" prop="roughWeight">
				<el-input-number v-model="formData.roughWeight" :min="-9999" :max="9999" :precision="3" :step="0.001"
					controls-position="right" placeholder="±值" style="width: 180px;" />
				<span style="margin-left: 8px; color: #666;">吨（±值）</span>
			</el-form-item>



			<el-form-item label="结算净重" prop="suttle">
				<el-input-number v-model="formData.suttle" :min="0.000" :max="10" :precision="3" :step="0.01"
					controls-position="right" placeholder="结算系数" style="width: 180px;" />
				<span style="margin-left: 8px; color: #666;">系数（0.001-1）</span>
			</el-form-item> -->
			<!-- <el-form-item label="打印入库模版" prop="storeModelId">
					<el-select  v-model="formData.storeModelId" placeholder="请选择磅单类型" style="width: 180px;">
						<el-option label="盛虹入库" :value="1"></el-option>
						
						<el-option label="天津大港入库" :value="3"></el-option>
					
						<el-option label="默认磅单" :value="5"></el-option>
					</el-select>
			</el-form-item>
			<el-form-item label="打印出库模版" prop="outModelId" >
					<el-select  v-model="formData.outModelId" placeholder="请选择磅单类型" style="width: 180px;">
						
						<el-option label="盛虹出库" :value="2"></el-option>
					
						<el-option label="天津大港出库" :value="4"></el-option>
						<el-option label="默认磅单" :value="5"></el-option>
					</el-select>
			</el-form-item> -->


		</el-form>

		<template #footer>
			<el-button @click="resetForm(formRef)">取消</el-button>
			<el-button type="primary" @click="handleSubmit">确定</el-button>
		</template>
	</el-dialog>


</template>

<script setup lang="ts">
	import {
		ref,
		reactive,
		onMounted,
		onBeforeUnmount,
		getCurrentInstance
	} from 'vue';
	import poundImg from '@/assets/pound.png';
	import { ElMessage, ElMessageBox } from 'element-plus';
	import kache from '@/assets/kache.png';
	import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

	const size = ref<ComponentSize>('default')
	import { Plus, ArrowLeft } from '@element-plus/icons-vue'
	import { useRouter } from 'vue-router'
	const {
		proxy
	} = getCurrentInstance()
	const router = useRouter()
	const dialogVisible = ref(false)
	const formRef = ref<FormInstance>()
	const dialogTitle = ref('新增货物')
	const currentEditId = ref<number | null>(null)
	const actionType = ref('add')
	const searchForm = reactive({
	  cargoName: '',    // 检索用的货物名称
	  specifications: ''// 检索用的规格
	});
	const defaultFormData = {
		
		id: null,
		cargoName: '',
		specifications: '',
		
		
	}
	const formData = reactive({ ...defaultFormData })

	const rules = reactive<FormRules>({

		cargoName: [{ required: true, message: '请输入货物名称', trigger: 'blur' }],

		roughWeight: [
			{
				required: true,
				validator: (_, value, callback) => {
					if (value === null || value === undefined) {
						callback(new Error('请输入毛重扣重值'))
					} else if (value < -9999 || value > 9999) {
						callback(new Error('毛重扣重范围：-9999 ~ 9999'))
					} else {
						callback()
					}
				},
				trigger: 'blur'
			}
		],
		// tare: [
		// 	{
		// 		required: true,
		// 		validator: (_, value, callback) => {
		// 			if (value === null || value === undefined) {
		// 				callback(new Error('请输入皮重扣重值'))
		// 			} else if (value < -9999 || value > 9999) {
		// 				callback(new Error('皮重扣重范围：-9999 ~ 9999'))
		// 			} else {
		// 				callback()
		// 			}
		// 		},
		// 		trigger: 'blur'
		// 	}
		// ],
		// suttle: [
		// 	{
		// 		required: true,
		// 		validator: (_, value, callback) => {
		// 			if (value === null || value === undefined) {
		// 				callback(new Error('请输入结算系数'))
		// 			} else if (value < 0.001 || value > 10) {
		// 				callback(new Error('结算系数范围：0.001 ~ 10'))
		// 			} else {
		// 				callback()
		// 			}
		// 		},
		// 		trigger: 'blur'
		// 	}
		// ]
	})
	const cargoOptions = ref<CargoOption[]>([
		
	])
	const resetSearch = () => {
	  // 清空检索表单
	  searchForm.cargoName = '';
	  searchForm.specifications = '';
	  // 重置页码为第1页（避免清空后仍停留在原分页）
	  listQuery.current = 1;
	  // 重新加载数据
	  fetchData();
	};
	
	const handleCargoChange = (val: string, formData: Record<string, any>) => {
			
		  // 查找匹配的货物项
		  const matchingCargo = cargoOptions.value.find(
		    (cargo) => formData.cargoName === cargo.cargoName
		  );
		
		  if (matchingCargo) {
		    // 将匹配项的规格赋值给formData
		    formData.specifications = matchingCargo.specifications;
		  } 
		
		if (!cargoOptions.value.some(item => item.id === val)) {
			
			cargoOptions.value.push({
				cargoName: val,
				id: val
			})
		}
		
	}
	// 重置
	const resetForm = () => {
	
		formRef.value?.resetFields()

	
		Object.assign(formData, defaultFormData)

	
		dialogVisible.value = false
	}

	// 编辑按钮点击
	const handleEdit = (row : any) => {
		actionType.value = 'edit'
		dialogTitle.value = '编辑货物'
		currentEditId.value = row.id

		// 填充表单数据
		Object.keys(formData).forEach(key => {
		    if (row.hasOwnProperty(key)) {
		      // 处理需要转换的字段
		      if (['storeModelId', 'outModelId'].includes(key)) {
		        formData[key] = Number(row[key]) || 5
		      } else {
		        formData[key] = row[key]
		      }
		    }
		  })

		dialogVisible.value = true
	}
	const handleDelete = (row : any) => {
		ElMessageBox.confirm('确定要删除这条扣重规则吗？', '删除确认', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(async () => {
			try {
				const res = await proxy.$request.deleteRule(row.id)
				if (res.data.code === 200) {
					ElMessage.success('删除成功!')
					fetchData()
				} else {
					ElMessage.error(res.data.message || '删除失败')
				}
			} catch (error) {
				console.error('删除失败:', error)
				ElMessage.error('删除失败，请稍后重试')
			}
		}).catch(() => {
			// 用户取消删除
		})
	}
	const filterEmptyFields = (obj : any) => {
			
		return Object.entries(obj).reduce((acc, [key, value]) => {
			if (value !== '' && value !== null && value !== undefined) {
				acc[key] = value
			}
			console.log('啊',acc)
			return acc
		}, {})
	}
	const getCargoNameList = async () => {
		try {
	
	
			const res = await proxy.$request.getCargoNameList()
			 cargoOptions.value=[]
			if (res?.data?.code === 200) {
			
				
				if(res.data.result){
				 cargoOptions.value = res.data.result
				}
			
				
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.message || '网络请求异常')
		}
	}

	const handleSubmit = async () => {
		try {
			await formRef.value?.validate()
			
		
			console.log('提交数据:', filterEmptyFields(formData))

			proxy.$request.setRule(formData).then((res => {

				if (res.data.code === 200) {

					ElMessage.success(res.data.message)

					const formEl = formRef.value
					resetForm()
					fetchData()

				} else {

					ElMessage.error(res.data.message)
				}
			})).catch((err => {
				console.log('err', err)
				ElMessage.error(err);
			}))


			// dialogVisible.value = false
		} catch (error) {
			console.log('表单验证失败:', error)
		}
	}

	defineExpose({
		open: () => {
			dialogVisible.value = true
			formRef.value?.resetFields()
		}
	})
	const newlist = () => {
		actionType.value = 'add'
		dialogTitle.value = '新增货物'
		resetForm()
		dialogVisible.value = true
	}
	const handleBack = () => {
		router.go(-1)
	}

	const tableData = ref([])


	const listQuery = reactive({
		current: 1,
		size: 5,

	})

	const total = ref(0)

	const fetchData = async () => {
	  try {
	    // 合并分页参数 + 检索参数（过滤空值，避免无效参数）
	    const queryParams = {
	      ...listQuery,  // 原有分页参数（current/pageSize）
	      ...filterEmptyFields(searchForm)  // 新增检索参数（过滤空值）
	    };
	
	    // 调用接口时传入合并后的参数（原代码是只传 listQuery，此处修改）
	    const res = await proxy.$request.getDeductWeight(queryParams);
	
	    if (res?.data?.code === 200) {
	      tableData.value = res.data.result?.resultData || [];
	      total.value = res.data.result?.totalRows || 0;
	    } else {
	      ElMessage.error(res?.data?.message || '请求失败');
	    }
	  } catch (error: any) {
	    console.error('API请求错误:', error);
	    ElMessage.error(error.message || '网络请求异常');
	  }
	};


	const handleSizeChange = (val : number) => {
		 listQuery.size = val; // 补充原代码缺失的分页尺寸赋值（避免切换每页条数无效）
		fetchData()
	}
	const handleCurrentChange = (val : number) => {
		listQuery.current = val; // 补充原代码缺失的页码赋值
		fetchData()
	}

	const onSubmit = () => {
		fetchData()
	}



	onMounted(() => {
		fetchData()
		getCargoNameList()
	})
</script>

<style lang="scss" scoped>
	.pound-container {
	  padding: 28px;
	  box-sizing: border-box;
	  position: relative;
	
	  .pound-bottom {
	    width: 100%;
	    margin-top: 50px;
	  }
	
	  // 新增：检索区域响应式适配（小屏幕自动换行）
	  .search-container {
	    flex-wrap: wrap;
	    padding: 8px 0;
	
	    // 适配小屏幕时，每个检索项占满宽度
	    @media (max-width: 768px) {
	      el-form-item {
	        width: 100%;
	        margin-bottom: 8px !important;
	      }
	      el-input {
	        width: 100% !important;
	      }
	    }
	  }
	}
</style>